/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package merlion.common.mdb;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.ejb.EJB;
import javax.ejb.EJBException;
import javax.mail.Message;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import merlion.common.util.Consts;
import merlion.crm.slcm.entity.ContactRecord;
import merlion.frm.bpm.entity.Invoice;
import merlion.frm.bpm.session.SalesBPSessionBeanLocal;

/**
 *
 * @author Zhang Ying
 */
public class EmailManager {

    String emailServerName = "smtp.gmail.com";
    String emailFromAddress = "is3102m01<is3102m01@gmail.com>";
    String toEmailAddress = "is3102m01<is3102m01@gmail.com>";
    String mailer = "JavaMailer";
    @EJB
    private SalesBPSessionBeanLocal bpSession;

    public EmailManager() {
    }

    public String emailAccountActivation(String staffName, String pwd, String toEmailAddr, String token) {
        toEmailAddress = toEmailAddr;
        String infoText = "Hello " + staffName + ".\n\n"
                + "Your password is " + pwd + ".\n\n "
                + "Your account is still not activated. \n\nPlease click the following link for account activation: \n\n";
        String callbackUrl = "'" + Consts.ACCOUNT_ACTIVATION_CALLBACK_URL + "?token=" + token + "'";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Activate your Account");
                String messageText = infoText + callbackUrl;
                msg.setText(messageText);
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }

    public String emailAccountReactivation(String username, String toEmailAddr, String token, String password) {
        toEmailAddress = toEmailAddr;
        String infoText = "Hello " + username + ",\n\n" + "You account has been disabled because you just reset your password."
                + "\n\n Please click the following link for account re-activation: \n\n";
        String callbackUrl = "'" + Consts.ACCOUNT_REACTIVATION_CALLBACK_URL + "?token=" + token + "'";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Re-activate your Account");
                String messageText = infoText + callbackUrl;
                msg.setText(messageText);
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }

    public String emailLoginFail(String username, String toEmailAddr, String token, String password) {
        toEmailAddress = toEmailAddr;
        String infoText = "Hello " + username + ",\n\n" + "You account has been disabled because you failed loggin in too many times."
                + "\n\n Please call tech staff to reset your password.";
        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Re-activate your Account");
                String messageText = infoText;
                msg.setText(messageText);
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }

    public String emailResetPwd(String username, String toEmailAddr, String token, String password) {
        toEmailAddress = toEmailAddr;
        String infoText = "Hello " + username + ",\n\n" + "You account has been disabled because the admin has just reset your password to " + password + "."
                + "\n\n Please click the following link for account re-activation and password change: \n\n";
        String callbackUrl = "'" + Consts.ACCOUNT_ACTIVATION_CALLBACK_URL + "?token=" + token + "'";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Re-activate your Account");
                String messageText = infoText + callbackUrl;
                msg.setText(messageText);
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
            return token;
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }

    public boolean emailSalesQuotation(String toEmailAddr, Long sqId, byte[] sqContents) {
        toEmailAddress = toEmailAddr;
        String infoText = "Dear Customer\n\n" + "Here is your sales quotation."
                + "\n\nIf you have any problems with it, please kindly proceed to our staff at (65)6516 6731. \n\n"+"Best Regards,\nMerlion\n\n"
                +"This is a system generated email. Please do not reply.";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);
            MimeMultipart mp = new MimeMultipart();

            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Your Sales Quotation from SSAP Merlion");

                // create the message part
                MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                String messageText = infoText;
                messageBodyPart1.setText(messageText);
                mp.addBodyPart(messageBodyPart1);

                // set attachment
                MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                //DataSource source = new FileDataSource("C:\\Users\\Zhang Ying\\Desktop\\a.txt");
                //messageBodyPart2.setDataHandler(new DataHandler(source));
                
                messageBodyPart2.setContent(sqContents, "application/pdf");
                
                //TODO: may need to change this
                messageBodyPart2.setFileName("salesQuation.pdf");
                mp.addBodyPart(messageBodyPart2);

                // put parts in message
                msg.setContent(mp);

                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }
    
    public void emailInvoiceDueSoon(String invoiceId, String email, String cn, String timeStr) {
        //Invoice invoice = bpSession.getInvoiceById(invoiceId);
        toEmailAddress = email;

        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String infoText = "Dear " + cn + ".\n\n"
                + "Your invoice is going to be due on " + timeStr + ".\n\n "
                + "Please pay soon.\n\nBest Regards,\nMerlion\n\n\nThis is a system generated email.Please do not reply.";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Invoice due reminder");
                String messageText = infoText;
                msg.setText(messageText);
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }
    
     public void emailInvoiceDueDefault(String invoiceId, String email, String companyName) {
        System.out.println("Email Manager: emailInvoiceDueDefault - invoiceId: " + invoiceId);
        //Invoice invoice = bpSession.getInvoiceById(invoiceId);
        toEmailAddress = email;
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        String infoText = "Hello " + companyName + ".\n\n"
                + "Your invoice " + invoiceId + " has dued and you have not make your payment promtply.\n\n "
                + "You have been marked as default in our system and your orders will be blocked from further processing.\n\n"
                + "Please pay soon.\n\nBest Regards,\nMerlion\n\n\nThis is a system generated email.Please do not reply.";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);
            Message msg = new MimeMessage(session);
            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Invoice customer default reminder");
                String messageText = infoText;
                msg.setText(messageText);
                msg.setHeader("X-Mailer", mailer);
                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }

        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }

    public void emailInvoice(String email, Long invId, byte[] invContents) {
        toEmailAddress = email;
        String infoText = "Dear Customer.\n\n" + "Here is your invoice."
                + "\n\nIf you have any problems with it, kindly proceed to our staff at (65) 6516 6731. \n\n"+
                "Best Regards,\nMerlion\n\nThis is a system generated email, please do not reply.";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);
            MimeMultipart mp = new MimeMultipart();

            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Your Invoice from SSAP Merlion");

                // create the message part
                MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                String messageText = infoText;
                messageBodyPart1.setText(messageText);
                mp.addBodyPart(messageBodyPart1);

                // set attachment
                MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                //DataSource source = new FileDataSource("C:\\Users\\Zhang Ying\\Desktop\\a.txt");
                //messageBodyPart2.setDataHandler(new DataHandler(source));
                
                messageBodyPart2.setContent(invContents, "application/pdf");
                
                //TODO: may need to change this
                messageBodyPart2.setFileName("invoice.pdf");
                mp.addBodyPart(messageBodyPart2);

                // put parts in message
                msg.setContent(mp);

                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }

    void emailRawMaterialPurchaseOrer(String email, Long invId, byte[] invContents) {
        toEmailAddress = email;
        String infoText = "Dear Supplier.\n\n" + "Here is our raw material purchase order."
                + "\n\nIf you have any problems with it, please kindly proceed to our staff at (65) 6516 6731.\n\n"
                +"Best Regards,\n\nMerlion\n\nThis is a system generated email, please do not reply.";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);
            MimeMultipart mp = new MimeMultipart();

            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Our raw material purchase order from SSAP Merlion");

                // create the message part
                MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                String messageText = infoText;
                messageBodyPart1.setText(messageText);
                mp.addBodyPart(messageBodyPart1);

                // set attachment
                MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                //DataSource source = new FileDataSource("C:\\Users\\Zhang Ying\\Desktop\\a.txt");
                //messageBodyPart2.setDataHandler(new DataHandler(source));
                
                messageBodyPart2.setContent(invContents, "application/pdf");
                
                //TODO: may need to change this
                messageBodyPart2.setFileName("rawMaterialPurchaseOrder.pdf");
                mp.addBodyPart(messageBodyPart2);

                // put parts in message
                msg.setContent(mp);

                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }

    void emailReceipt(String email, Long invId, byte[] invContents) {
        toEmailAddress = email;
        String infoText = "Dear Customer.\n\n" + "Here is your receipt."
                + "\n\nIf you have any problems with it, please kindly proceed to our staff at (65) 6516 6731.\n\n"
                +"Best Regards,\n\nMerlion\n\nThis is a system generated email. Please do not reply.";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);
            MimeMultipart mp = new MimeMultipart();

            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Your receipt from SSAP Merlion");

                // create the message part
                MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                String messageText = infoText;
                messageBodyPart1.setText(messageText);
                mp.addBodyPart(messageBodyPart1);

                // set attachment
                MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                //DataSource source = new FileDataSource("C:\\Users\\Zhang Ying\\Desktop\\a.txt");
                //messageBodyPart2.setDataHandler(new DataHandler(source));
                
                messageBodyPart2.setContent(invContents, "application/pdf");
                
                //TODO: may need to change this
                messageBodyPart2.setFileName("receipt.pdf");
                mp.addBodyPart(messageBodyPart2);

                // put parts in message
                msg.setContent(mp);

                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }

    void emailSalesOrder(String email, Long invId, byte[] invContents) {
        toEmailAddress = email;
        String infoText = "Dear Customer.\n\n" + "Here is your sales order."
                + "\n\nIf you have any problems with it, please kindly proceed to our staff at (65) 6516 6731.\n\n"
                +"Best Regards,\n\nMerlion\n\nThis is a system generated email. Please do not reply.";

        try {
            Properties props = new Properties();
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");

            javax.mail.Authenticator auth = new SMTPAuthenticator();
            Session session = Session.getInstance(props, auth);
            session.setDebug(true);

            MimeMessage msg = new MimeMessage(session);
            MimeMultipart mp = new MimeMultipart();

            if (msg != null) {
                msg.setFrom(InternetAddress.parse(emailFromAddress, false)[0]);
                msg.setRecipients(Message.RecipientType.TO, InternetAddress.parse(toEmailAddress, false));
                msg.setSubject("Your Sales Order from SSAP Merlion");

                // create the message part
                MimeBodyPart messageBodyPart1 = new MimeBodyPart();
                String messageText = infoText;
                messageBodyPart1.setText(messageText);
                mp.addBodyPart(messageBodyPart1);

                // set attachment
                MimeBodyPart messageBodyPart2 = new MimeBodyPart();
                //DataSource source = new FileDataSource("C:\\Users\\Zhang Ying\\Desktop\\a.txt");
                //messageBodyPart2.setDataHandler(new DataHandler(source));
                
                messageBodyPart2.setContent(invContents, "application/pdf");
                
                //TODO: may need to change this
                messageBodyPart2.setFileName("salesOrder.pdf");
                mp.addBodyPart(messageBodyPart2);

                // put parts in message
                msg.setContent(mp);

                Date timeStamp = new Date();
                msg.setSentDate(timeStamp);
                Transport.send(msg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new EJBException(e.getMessage());
        }
    }
}
